package com.J.Plane;

import static android.opengl.GLES10.glDrawElements;
import static android.opengl.GLES10.glEnable;
import static android.opengl.GLES10.glFrontFace;
import static android.opengl.GLES10.glTexCoordPointer;
import static android.opengl.GLES10.glVertexPointer;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import junit.framework.Assert;



/**
 * This guy draws triangle on 3d.
 * 
 */
public class Triangle3D {

	private final static int VERTS = 3;
	private FloatBuffer mVertexBuffer;
	private FloatBuffer mTexBuffer;
	
	/*
	 * Share index buffer for 
	 * performance & memory usage optimization.
	 */
	static private ShortBuffer gIndexBuffer;	
	static {
		ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2);
		ibb.order(ByteOrder.nativeOrder());
		gIndexBuffer = ibb.asShortBuffer();
		
		for (int i = 0; i < VERTS; i++) {
			gIndexBuffer.put((short) i);
		}
		gIndexBuffer.position(0);
	}

	public Triangle3D() {
		allocateBuffers();
	}

	public Triangle3D(Vector3[] verticies, NumberUV[] uv) {
		this();
		setVertexTexturePoints(verticies, uv);
	}

	
	/**
	 * Allocate buffers
	 */
	private void allocateBuffers() {
		ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4);
		vbb.order(ByteOrder.nativeOrder());
		mVertexBuffer = vbb.asFloatBuffer();

		ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4);
		tbb.order(ByteOrder.nativeOrder());
		mTexBuffer = tbb.asFloatBuffer();

		
	}
	
	
	/**
	 * Set vertex and texture points.
	 * The length for each data should be same with VERTS.
	 * 
	 * @param verticies	Vertex
	 * @param uv
	 */
	public void setVertexTexturePoints(Vector3[] verticies, NumberUV[] uv) {
		Assert.assertEquals(verticies.length, VERTS);
		Assert.assertEquals(uv.length, VERTS);
		
		mVertexBuffer.position(0);
		mTexBuffer.position(0);
		
		for (int i = 0; i < VERTS; i++) {
			mVertexBuffer.put(verticies[i].x);
			mVertexBuffer.put(verticies[i].y);
			mVertexBuffer.put(verticies[i].z);
			mTexBuffer.put(uv[i].u);
			mTexBuffer.put(uv[i].v);
		}
		
		mVertexBuffer.position(0);
		mTexBuffer.position(0);
	}
	
	/**
	 * Draw triangle
	 */
	public void render() {
        glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
		glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer);
		glDrawElements(
				GL10.GL_TRIANGLE_STRIP, 
				VERTS, 
				GL10.GL_UNSIGNED_SHORT,
				gIndexBuffer);
	}
}
